import { login, logout, getInfo, getUserInfo,getUserDetails, loginSuccess,submitLogin,smsLogin } from '@/api/user'
import { getToken, setToken, removeToken,removeNewToken,getNewToken,setNewToken} from '@/utils/auth'
import router, { resetRouter } from '@/router'
import axios from 'axios'
import qs from 'querystring'
import { stat } from 'fs'
const clientSetting = {
  // scope: 'AirERP',
  // username: '',
  // password: '',
  // grant_type: 'password',
  employee_no:'',
  token:null,
  grant_type: 'link_system',
  client_id: public_config.VUE_APP_CLIENT_ID,
  client_secret: public_config.VUE_APP_CLIENT_SECRET
}

const state = {
  token: getToken(),
  newToken:getNewToken(),
  name: '',
  userInfoData:null,
  workNumber:'',
  userName: '',
  avatar: '',
  email: '',
  introduction: '',
  phoneNumber: '',
  roles: [],
  details: '',
  permissions: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NEWTOKEN:(state, token) => {
    state.newToken = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERNAME: (state, userName) => {
    state.userName = userName
  },
  SET_TEL: (state, phoneNumber) => {
    state.phoneNumber = phoneNumber
  },
  SET_AVATAR: (state, avatar) => {
    // if (!avatar) avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  },
  SET_USER_DETAILS: (state, details) => {
    state.details = details
  },
  SET_USER_INFO:(state, data) => {
    state.userInfoData = data
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  CLEAN: state => {
    state.token = ''
    state.newToken = ''

    state.name = ''
    state.userName = ''
    state.workNumber = ''
    state.avatar = ''
    state.email = ''
    state.introduction = ''
    state.phoneNumber = ''
    state.roles = []
    state.permissions = []
    state.details = ''
    state.userInfoData =null
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // clientSetting.username = userInfo?.employee_no.trim() 
      // clientSetting.password = userInfo?.password
      clientSetting.employee_no = userInfo?.employee_no.trim() 
      clientSetting.token = userInfo?.token
      const serv = axios.create({
        timeout: 5000 // request timeout
      })
      // login(clientSetting)
      //   .then(response => {
      //     commit('SET_TOKEN', response.access_token)
      //     setToken(response.access_token).then(() => {
      //       resolve()
      //     })
      //   })
      //   .catch(error => {
      //     reject(error)
      //   })
      serv({
        url: public_config.auth_api + '/connect/token',
        headers: {
          'applicationName': 'CentralControl',
          'content-type': 'application/x-www-form-urlencoded',
          'Accept-Language': 'zh-Hans,zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6'
        },
        method: 'post',
        data: qs.stringify({ ...clientSetting })
      }).then(async res => {
        console.log('执行了一次token请求')
        if (res.status === 200) {
          const { data } = res
          // console.log('登录成功',data)
          commit('SET_TOKEN', data.access_token)
          await setToken(data.access_token)
          loginSuccess()
          resolve(data.access_token)
        } else {
          reject('Error')
        }
      }, err => {
        reject(err)
      })
    })
  },
  /*
  融合登录
  */
    // 账号登录
    LoginWay({ commit }, userInfo) {
      const workNumber = userInfo.workNumber.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        submitLogin(workNumber, password, code, uuid).then(res => {
          setNewToken(res.data.token)
          
          commit('SET_NEWTOKEN', res.data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    //手机登录
    smsLoginWay({ commit }, userInfo) {
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        smsLogin(userInfo).then(res => {
          setNewToken(res.data.token)
          commit('SET_TOKEN', res.data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    getUserInfo({ commit, state }){
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then(res => {
            commit('SET_USER_INFO', JSON.stringify(res.data))
            commit('SET_USERNAME', res.data.user.userName)
            commit('SET_PERMISSIONS', res.data.permissions)
            resolve(res.data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          if (!response) {
            reject('Verification failed, please Login again.')
          }
          const { userName, name, phoneNumber, email, extraProperties } = response
          getUserDetails({ jobNum: userName }).then(res => {

            commit('SET_USER_DETAILS', JSON.stringify(res))
          })
          commit('SET_NAME', name)
          commit('SET_USERNAME', userName)
          commit('SET_TEL', phoneNumber)
          commit('SET_AVATAR', extraProperties.Avatar)
          commit('SET_EMAIL', email)
          commit('SET_INTRODUCTION', extraProperties.Introduction)
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 设置角色
  setRoles({ commit }, roles) {
    commit('SET_ROLES', roles)
  },

  // // user logout
  // logout({ commit, state, dispatch }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       commit('SET_TOKEN', '')
  //       commit('SET_ROLES', [])
  //       removeToken()
  //       resetRouter()

  //       // reset visited views and cached views
  //       // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
  //       dispatch('tagsView/delAllViews', null, { root: true })

  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  // user logout
  logout({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          commit('CLEAN')
          removeToken().then(() => {
            removeNewToken()
            resetRouter()
            // reset visited views and cached views
            // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
            dispatch('tagsView/delAllViews', null, { root: true })

            resolve()
          })
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('CLEAN')
      removeToken().then(() => {
        removeNewToken()
        resolve()
      })
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
